<?php

class OrdersController extends CController {
	public $baseUrl;
	public $isOrders;
	public $login;
	public $title;
	public $categories;

	public function init() {
		$this->baseUrl = Yii::app()->request->baseUrl;
		$this->isOrders = true;
		$session = new CHttpSession;
		$session->open();
		$this->login = $session['login'];
		$session->close();

		$this->title = 'Заказы';
		$this->categories = array(
			'index' => array('title' => 'Новые', 'url' => CHtml::normalizeUrl(array('orders/index', 'status'=>'Новый'))),
			'processed' => array('title' => 'В обработке', 'url' => CHtml::normalizeUrl(array('orders/index', 'status'=>'В обработке'))),
			'back' => array('title' => 'Отмененые', 'url' => CHtml::normalizeUrl(array('orders/index', 'status'=>'Отменен'))),
			'okay' => array('title' => 'Доставленные', 'url' => CHtml::normalizeUrl(array('orders/index', 'status'=>'Доставлен'))),
		);
	}

	public function actionIndex($status) {
		switch($status){
			case 'Новый':
				$state='index';
				break;
			case 'В обработке':
				$state='processed';
				break;
			case 'Отменен':
				$state='back';
				break;
			case 'Доставлен':
				$state='okay';
				break;
		}
		$this->categories[$state]['active'] = true;
		$data['orders'] = Orders::model()->findAll(array('condition'=>'`status`=:stats', 'params'=>array(':stats'=>$status), 'order'=>'id DESC'));
		$this->render('orders', $data);
	}

	public function actionView($id){
		$data['order'] = Orders::model()->findByPk($id);
		$data['items_new']= Catalog::model()->findAll();
		$this->renderPartial('view', $data);
	}

	public function actionDelete($id){
		$model = Orders::model()->findByPk($id);
		$model->delete();
		$this->redirect(CHtml::normalizeUrl(array('orders/index','status'=>'Новый')));

	}
	public function actionSaveOrder($id){
		$record = Orders::model()->findByPk($id);
		$items=Yii::app()->getRequest()->getPost('items');
		$order=Yii::app()->getRequest()->getPost('order');

		$order['full_price']=0;
		$not_del=array();
		foreach ($items as $item => $count) {
			$record_item=$record->ordersItems(array('condition'=>'id_item=:id', 'params'=>array(':id'=>$item)));
			if($record_item){
				$record_item[0]->attributes=array('count'=>$count);
				$record_item[0]->save();
				$order['full_price']+=$record_item[0]->count*$record_item[0]->price;
				$not_del[]=$record_item[0]->id;
			}else{
				$item_new=Catalog::model()->findByPk($item);
				$record_item= new OrdersItem();
				$record_item->id_order=$id;
				$record_item->id_item=$item_new->id;
				$record_item->count=$count;
				$record_item->price=$item_new->price;
				$record_item->save();
				$order['full_price']+=$record_item->count*$record_item->price;
				$not_del[]=$record_item->id;
			}
		}
		$q=new CDbCriteria();
		$q->addNotInCondition('`id_item`', $not_del);
		$q->addCondition('`id`='.$record->id.'');
		OrdersItem::model()->deleteAll($q);
		$order['full_price']+=$order['delivery_price'];
		$record->attributes = $order;
		$record->save();
		$this->redirect(CHtml::normalizeUrl(array('orders/index','status'=>'Новый')));
	}
	public function actionPrint($id) {
		$this->layout = "print";
		$data['order']=Orders::model()->findByPk($id);
		$this->render('print', $data);
	}

	public function actionAddItem($id)
	{
		$data['item']=Catalog::model()->findByPk($id);
		$this->renderPartial('AddItem', $data);
	}
	public function actionSendPopup()
	{
		$data['id']=Yii::app()->getRequest()->getPost('id');
		$data['status']=Yii::app()->getRequest()->getPost('status');
		switch($data['status']){
			case 'В обработке':
				$templ='processed_order';
				break;
			case 'Отмененный':
				$templ='back_order';
				break;
			case 'Доставлен':
				$templ='okay_order';
				break;
		}

		$data['mail']=MailTemplate::model()->findByAttributes(array('name'=>$templ));
		$this->renderPartial('SendPopup',$data);
	}
	public function actionSendMessage($id, $status)
	{
		$order=Orders::model()->findByPk($id);

		$body=Yii::app()->getRequest()->getPost('body');
		$mail_title=Yii::app()->getRequest()->getPost('mail_title');
		$templ['number_order']=$order->id;
		$templ['restaurant']=$order->idRestaurant->name;
		$templ['name']=$order->name;
		$templ['address']=$order->address;
		$templ['phone']=$order->phone;
		$templ['message']=$order->message;
		$templ['mail']=$order->email;
		$templ['full_price']=$order->full_price;
		$templ['items']='<table class="table">
					<thead>
						<tr>
							<td> Код товара </td>
                            <td> Название</td>
							<td> Количество </td>
							<td> Цена за единицу</td>
							<td> Цена </td>
						</tr>
					</thead>
					<tbody>';
		foreach ($order->ordersItems as $item) {
			$templ['items'].='<tr>
							<td> '.$item->id.' </td>
							<td> '.$item->idItem->title.'</td>
							<td> '.$item->count.'</td>
							<td> '.$item->idItem->price.'</td>
							<td>'.$item->count*$item->idItem->price.' </td>
						</tr>';
		}
		if (SendMail::send($order->email,'new_order_user',$templ, $body, $mail_title)) {
			$order->status=$status;
			$order->save();
			if(Yii::app()->request->isAjaxRequest){
				$data['url']=CHtml::normalizeUrl(array('orders/index','status'=>'Новый'));
				echo json_encode($data);
				Yii::app()->end();
			}else{
				$this->redirect(CHtml::normalizeUrl(array('orders/index','status'=>'Новый')));
			}
		}
	}
}		
